/*
 * messaging_pipe.cpp
 *
 *  Created on: 20 Oca 2012
 *      Author: root
 */

#include "messaging_pipe.h"
#include <cstring>

namespace androidplus {
namespace messaging {

int create_pipe(int *read_channel, int *write_channel) {
	LOGI("Creating Pipe");
	int pipe_fd[2];

	if (pipe(pipe_fd) < 0) {
		LOGF("Pipe Fatal:%s", strerror(errno));
		return errno * -1;

	}
	*read_channel = pipe_fd[0];
	*write_channel = pipe_fd[1];
	LOGI("Pipe Successfull");
	return 0;
}

messaging_pipe::messaging_pipe() {
	channel_read = 0;
	channel_write = 0;
	//TODO this is fatal we must initialize first and check status of creating pipe
	create_pipe(&channel_read, &channel_write);

}

messaging_pipe::~messaging_pipe() {
	close(channel_read);
	close(channel_write);
}

int messaging_pipe::fd() const {
	return channel_read;
}

int messaging_pipe::write_message(const message *msg) throw () {
	//LOGI("Writing To Pipe msg:%d ", msg->msg_number());
	int tmp = msg->msg_number();
	if (channel_write == 0) {
		int res = create_pipe(&this->channel_read, &this->channel_write);
		if (res)
			return res;
	}
	if (write(channel_write, &tmp, sizeof(tmp)) < sizeof(tmp)) {
		LOGF("Write Pipe Fatal:%s", strerror(errno));
		return errno * -1;
	}
    message *tmp_msg=const_cast<message *>(msg);
    if(tmp_msg==NULL)
    	LOGF("casting is NULL FATAL");
	queue.push_back(tmp_msg);
    //LOGI("Writing To Pipe Successful Msg:%d",msg->msg_number());
	return 0;

}

int messaging_pipe::read_message(message **msg) throw () {
	int tmp;
	//LOGI("Reading From Pipe");
	if (channel_read == 0) {
		int res = create_pipe(&this->channel_read, &this->channel_write);
		if (res)
			return res;
	}

	if (read(channel_read, &tmp, sizeof(tmp)) < sizeof(tmp)) {
		LOGF("Read Pipe Fatal:%s", strerror(errno));
		return errno * -1;
	}

	*msg = queue.front();
	queue.pop_front();
	//LOGI("Readed From Pipe Msg:%d", tmp);
	return 0;
}
}/*namespace messaging*/
} /* namespace AndroidPlus */
